package com.bjpowernode.gateway.mvc.controller;

import cn.hutool.core.util.StrUtil;
import com.bjpowernode.gateway.db.domain.PayWay;
import com.bjpowernode.gateway.mvc.models.dto.InvokeApiResultDto;
import com.bjpowernode.gateway.mvc.models.form.TradeConfirmForm;
import com.bjpowernode.gateway.mvc.models.form.TradeReceiveForm;
import com.bjpowernode.gateway.mvc.service.PaymentTradeService;
import com.bjpowernode.gateway.mvc.service.ThirdApiService;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Controller
public class PaymentTradeController {
    @Resource
    PaymentTradeService paymentTradeService;

    @Resource
    private Map<String,ThirdApiService> mapThirdApiService;

    @RequestMapping("/trade/receive")
    public String tradeReceive(TradeReceiveForm receiveForm, Model model){
        try {
            //验证数据
            String productNum = receiveForm.getProductNum();
            if(StrUtil.isNotBlank(productNum)&&Integer.parseInt(productNum)<1){
                throw new RuntimeException("产品数量必须大于0");
            }
            BigDecimal orderMoney = new BigDecimal(receiveForm.getOrderMoney());
            if(orderMoney.doubleValue()<0.01){
                throw new RuntimeException("订单金额不正确");
            }
            //验证userNo,productCode,appKey是否存在,sign
            List<PayWay> payWays = paymentTradeService.checkRequestSignGetPayWayList(receiveForm);
            //将接收的商品,支付人等信息和支付方式列表,存储到页面上
            model.addAttribute("origin",receiveForm);
            model.addAttribute("payWays",payWays);
            //展示支付方式,thymeleaf
            return "/payment/payWays";
        } catch (Exception e) {
            model.addAttribute("error",e.getMessage());
            e.printStackTrace();
        }
        return "error/showError";


    }
    @RequestMapping("/trade/confirm")
    public String tradeConfirm(TradeConfirmForm confirmForm, Model model){
        //调用service,生成order,调用第三方接口
        //使用策略设计模式:把各个支付方式的业务逻辑封装到独立的类中
        //根据支付方式,选择独立的类,执行其中的业务方法

        //KUAIQIAN:PC_PAY
        String wayCode = confirmForm.getWayTypeCode().split(":")[0];
        ThirdApiService thirdApiService = mapThirdApiService.get(wayCode);
        InvokeApiResultDto invokeApiResultDto = thirdApiService.invokePayment(confirmForm);
        //添加数据到Model
        model.addAttribute("pay",invokeApiResultDto);
        return invokeApiResultDto.getView();

    }
    @RequestMapping("/trade/order")
    @ResponseBody
    public String tradeOrder(@RequestBody String json){
        String result = paymentTradeService.obtainResult(json);
        return result;
    }
}
